package com.lzyyj.gmis.base.webui.action;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.SessionAware;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.lzyyj.common.ProxyWrapper;
import com.lzyyj.gmis.base.model.IUser;
import com.lzyyj.gmis.base.model.UserVo;
import com.lzyyj.gmis.base.service.IUserService;
import com.opensymphony.xwork2.ActionSupport;

@SuppressWarnings("rawtypes")
@Scope("prototype")
@Controller
public class LoginAction extends ActionSupport implements SessionAware {

	/**
	 * 
	 */
	private static final long serialVersionUID = -970142279068260362L;
		
	public static String CHECK_CODE_KEY = "CheckCode";
	
	public static String CURRENT_USER_KEY = "CurrentUser";

	private IUserService<?, ?> userService;

	public IUserService<?, ?> getUserService() {
		return userService;
	}

	public void setUserService(IUserService<?, ?> userService) {
		this.userService = userService;
	}
	
	public String title = "龙族雅云居-综合信息管理系统";

	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	private IUser user = new UserVo();
	
	private String checkCode;
	private Map<String, Object> session;
	private String submit;

	public String getSubmit() {
		return submit;
	}

	public void setSubmit(String submit) {
		this.submit = submit;
	}

	public String getCheckCode() {
		return checkCode;
	}

	public void setCheckCode(String checkCode) {
		this.checkCode = checkCode;
	}
	
	private String definedResult;
	
	public String getDefinedResult() {
		return definedResult;
	}
		
	public String login() {
		if (user == null||user.getLoginName()==null||user.getLoginName().length()==0) {
			if (session.containsKey(CHECK_CODE_KEY)){
				session.remove(CHECK_CODE_KEY);
			}
			return INPUT;
		} else {
			IUser userVo = ProxyWrapper.createProxyBean(IUser.class, "loginName,password", user);
			if (userVo.getLoginName() == null || userVo.getLoginName().trim().length()==0) {
				addFieldError("user.userName", "请输入登录名");
				HttpServletRequest request=ServletActionContext.getRequest();
				Cookie cookie[]=request.getCookies();
				if (cookie!=null){
					for(int i=0;i<cookie.length;i++){
						Cookie newCookie= cookie[i];
						if(newCookie.getName().equals("username")){
							String username="";
							try {
								username = URLDecoder.decode(newCookie.getValue(),"utf-8");
							} catch (UnsupportedEncodingException e) {
								e.printStackTrace();
							}
							userVo.setLoginName(username);
							break;
						}
					}
				}
			}
			
			String sessionCheckCode = null;
			if (session.containsKey(CHECK_CODE_KEY)){
				sessionCheckCode = (String)session.get(CHECK_CODE_KEY);
				if (checkCode == null || checkCode.trim().equals("")) {
					addFieldError("checkCode", "验证码不能为空 ");
				}
			}
			
			if (!hasErrors()) {
				
				if (sessionCheckCode==null || checkCode.equalsIgnoreCase(sessionCheckCode)) {
					Object currentUser = null;
					try {
						if (userService!=null){
							currentUser = userService.login(user.getLoginName(), user.getPassword());
						}else {
							currentUser = user;
						}
						if (null != currentUser) {
							session.put(CURRENT_USER_KEY, currentUser);
							HttpServletResponse response = ServletActionContext.getResponse();
							String username = "";
							try {
								username = URLEncoder.encode(userVo.getLoginName(),"utf-8");
							} catch (UnsupportedEncodingException e) {
								e.printStackTrace();
							}

							Cookie username_Cookie = new Cookie("username", username);
							response.addCookie(username_Cookie);
						} else {
							this.addActionError("您输入的用户名或密码不正确，请重新输入。");
							return ERROR;
						}
					} catch (Exception e) {
						addActionError("发生错误："+e.getMessage());
						return ERROR;
					}
				} else {
					this.addActionError("您输入的验证码和系统产生的不一致，请重新输入。");
					return ERROR;
				}
			}else {
				return ERROR;
			}
		}
		if (session.containsKey("prePage")){
			definedResult = (String)session.get("prePage");
			return "redirect";
		}else{
			return SUCCESS;
		}
	}

	public String logout() {
		session.remove(CURRENT_USER_KEY);	// 清除登录标志
		if (userService!=null){
//			userService.logout(user);// 告知业务层有注销业务
		}
		definedResult = "login";
		return "redirectAction";
	}

	public IUser getUser() {
		return user;
	}

	public void setUser(IUser user) {
		this.user = user;
	}

	public Map<String, Object> getSession() {
		return session;
	}

	public void setSession(Map<String, Object> session) {
		this.session = session;
	}

	public IUserService getUserManager() {
		return userService;
	}

	public void setUserManager(IUserService userManager) {
		this.userService = userManager;
	}
}